package com.example.autopia.view.Activities

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.util.Patterns
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import com.example.autopia.R
import com.example.autopia.databinding.ActivityAddCardBinding
import com.example.autopia.model.Item.Card
import com.example.autopia.model.Repositories.UsersRepository
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import java.util.Calendar
import kotlin.math.log

class AddCardActivity : AppCompatActivity() {
    private lateinit var binding: ActivityAddCardBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAddCardBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.apply {
            ibBack.setOnClickListener {
                finish()
            }
            btAddCard.setOnClickListener {
                /*val isValidated: Boolean = validateData(number, nameSurname, date, code)
                if (isValidated) {
                    //addCard
                    // сделать проверку что cvc код это int !!!!!!!!!!!!!!
                }*/
                if (etCardCvc.text.toString().isNotEmpty()) {
                    val cvc = etCardCvc.text.toString().toIntOrNull()
                    if (cvc != null) {
                        val isValidated: Boolean = validateData(
                            binding.etCardNumber.text.toString(),
                            etCardName.text.toString(),
                            etCardDate.text.toString(),
                            etCardCvc.text.toString().toInt()
                        )
                        if (isValidated) {
                            // все данные корректны, добавляем карту
                            val userCard = Card(
                                etCardNumber.text.toString(),
                                etCardName.text.toString(),
                                etCardDate.text.toString(),
                                etCardCvc.text.toString().toInt()
                            )
                            UsersRepository().addCard(
                                Firebase.auth.currentUser?.uid ?: "",
                                userCard
                            )
                            Toast.makeText(
                                this@AddCardActivity,
                                "Карта добавлена",
                                Toast.LENGTH_SHORT
                            ).show()
                            finish()
                        }
                    } else {
                        // cvc не является числом
                        binding.etCardCvc.error = "Некорректный CVC"
                    }
                } else {
                    Toast.makeText(
                        this@AddCardActivity,
                        "Необходимо заполнить все поля",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            etCardName.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    tvFio.text = s
                }

                override fun afterTextChanged(s: Editable?) {
                }
            })

            etCardNumber.addTextChangedListener(object : TextWatcher {
                private var isFormatting: Boolean = false
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }

                override fun afterTextChanged(s: Editable?) {
                    if (!isFormatting) {
                        isFormatting = true
                        val originalText = s.toString().replace(" ", "")
                        if (originalText.length <= 16) {
                            val formattedText = formatText(originalText)
                            etCardNumber.setText(formattedText)
                            etCardNumber.setSelection(formattedText.length)
                        } else {
                            etCardNumber.text.delete(18, etCardNumber.text.length)
                        }
                        isFormatting = false
                    }
                }

                private fun formatText(text: String): String {
                    val result = StringBuilder()
                    for (i in text.indices) {
                        if (i > 0 && i % 4 == 0) {
                            result.append(" ")
                        }
                        result.append(text[i])
                    }
                    return result.toString()
                }
            })

            etCardDate.addTextChangedListener(object : TextWatcher {
                private var isFormatting: Boolean = false
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    tvDate.text = s
                }

                override fun afterTextChanged(s: Editable?) {
                    if (!isFormatting) {
                        isFormatting = true
                        val originalText = s.toString().replace("/", "")
                        if (originalText.length <= 4) {
                            val formattedText = formatText(originalText)
                            etCardDate.setText(formattedText)
                            etCardDate.setSelection(formattedText.length)
                        } else {
                            etCardDate.text.delete(4, etCardDate.text.length)
                        }
                        isFormatting = false
                    }
                }

                private fun formatText(text: String): String {
                    val result = StringBuilder()
                    for (i in text.indices) {
                        if (i > 0 && i % 2 == 0) {
                            result.append("/")
                        }
                        result.append(text[i])
                    }
                    return result.toString()
                }
            })

            etCardCvc.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }

                override fun afterTextChanged(s: Editable?) {
                    if (s.toString().length > 3) {
                        etCardCvc.text.delete(2, etCardCvc.text.length)
                    }
                }
            })
        }
    }

    private fun validateData(
        number: String,
        nameSurname: String,
        date: String,
        code: Int
    ): Boolean {
        val originalTextNumber = number.replace(" ", "")
        val originalTextDate = date.replace("/", "")
        val pattern = Regex("^[0-9]+$")
        if (!pattern.matches(originalTextNumber) || originalTextNumber.length != 16) {
            binding.etCardNumber.error = "Некорректные данные"
            return false
        }
        if (nameSurname.length < 6) {
            binding.etCardName.error = "Слишком маленькая длина символов в поле"
            return false
        }
        if (nameSurname.length > 50) {
            binding.etCardName.error = "Слишком большая длина символов в поле"
            return false
        }
        if (!pattern.matches(originalTextDate) && originalTextNumber.length != 4) {
            binding.etCardName.error = "Некорректные данные"
            return false
        }
        val month = originalTextDate.substring(0, 2).toInt()
        val year = originalTextDate.substring(2, 4).toInt()
        val currentYear = Calendar.getInstance().get(Calendar.YEAR) % 100
        val currentMonth = Calendar.getInstance().get(Calendar.MONTH) + 1
        if (month == 0 || month > 12 || year < currentYear || (currentYear == year && currentMonth > month)) {
            binding.etCardDate.error = "Некорректные данные"
            return false
        }
        if (code.toString().length != 3) {
            binding.etCardCvc.error = "Некорректные данные"
            return false
        }
        return true
    }

    fun String.intOrString(): Any {
        return when (val v = toIntOrNull()) {
            null -> false
            else -> true
        }
    }
}